package com.wang.deploy;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.List;

@Component
public class CannalClient implements InitializingBean {
    private final static int BATCH_SIZE = 1000;


    @Override
    public void afterPropertiesSet() throws Exception {

        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress
                ("10.32.212.250", 11111), "example", "canal", "Canal@123456");
        try {
            //打开连接
            connector.connect();

            //订阅数据库，全部表
            connector.subscribe(".*\\..*");

            //回滚到未进行ack的地方，下次fetch的时候，可以从最后一个没有ack的地方开始拿
            connector.rollback();

            while (true) {
                //获取指定行的数据
                Message message = connector.getWithoutAck(BATCH_SIZE);
                //获取批量id
                long batchID = message.getId();
                //获取批量的数量
                int size = message.getEntries().size();
                //如果没有数据
                if (batchID == -1 || size == 0) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    //如果有数据，处理数据
                    printEntry(message.getEntries());
                }
                //进行batch id的确认。确认之后，小于等于此batchId的Message都会被确认。
                connector.ack(batchID);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connector.disconnect();
        }

    }

    //打印canal server解析binog获得实体类的信息
    private static void printEntry(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN ||
                    entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                //开启关闭事务的实体类型，跳过
                continue;
            }


            //rowChange对象包含了一行数据变化的所有特征
            //比如isDdl 是否是dl变跟数据操作的sql具体的ddl ssql beforeCoulumns afterColumns 变更前后的数据字段等
            CanalEntry.RowChange rowChange;
            try {
                rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR" + entry.toString(), e);
            }
            //获取操作类型：insert/update/delete类型
            CanalEntry.EventType eventType = rowChange.getEventType();
            //打印Header信息
            System.out.println(String.format("==============>;binlog[%s:%s] , name[%s,%s],eventType : %s",
                    entry.getHeader().getLogfileName(),entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(),entry.getHeader().getTableName(),
                    eventType
                    ));
            //判断是否是ddl语句
            if (rowChange.getIsDdl()) {
                System.out.println("==========>;isDdl:true,sql:"+rowChange.getSql());
            }

            for (CanalEntry.RowData rowData :rowChange.getRowDatasList()){
                //如果是删除语句
                if (eventType == CanalEntry.EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                }else if (eventType == CanalEntry.EventType.INSERT) {
                    printColumn(rowData.getAfterColumnsList());
                    //如果是更新的语句
                }else {
                    //变更前的数据
                    System.out.println("------>;before");
                    printColumn(rowData.getBeforeColumnsList());

                    //变更后的数据
                    System.out.println("------->after");
                    printColumn(rowData.getAfterColumnsList());
                    System.out.println("sql ##### " + rowChange.getSql());

                }
            }

        }
    }





    private static void printColumn(List<CanalEntry.Column> columns) {
        for (CanalEntry.Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }

}
